import { useSessionStore } from '@/store/session'
import { useWebSocket, type WebSocketStatus } from '@vueuse/core'
import { v7 as uuidv7 } from 'uuid'
import { closeToast } from 'vant'
import type { Ref } from 'vue'
import { ref } from 'vue'
import { FAction } from './constants'
import handleSocketMessage, { handleUserMessage } from './socketMessage'
import useWorker from "@/hooks/useWorker.ts";
import MyWorker from '@/worker/index.ts?worker'
const { close: closeRobotWorker } = useWorker(MyWorker)
class SocketServer {
  status: Ref<WebSocketStatus> = ref('CLOSED')
  data: Ref<any> = ref(null)
  send: (data: any) => void = () => {}
  close: () => void = () => {}
  constructor() {
    this.close = this.closeSocket.bind(this)
  }
  connect(transferMenu:any, connectType:any) {
    // 实现连接逻辑
    console.log('Connecting to the server...')
    const session = useSessionStore()
    const { status, data, send, close } = useWebSocket(session.websocketUrl, {
      autoClose: false,
      autoReconnect: {
        retries: 3,
        delay: 1000,
        onFailed: () => {
          console.log('websocket连接失败')
        },
      },
      heartbeat: {
        interval: 10000,
        message: JSON.stringify({
          type: 'page_ht',
          mid: 'ht_' + uuidv7(),
          sessionId: session.sessionId,
          configId: session.configId,
          meetingId: session.meetingId,
        }),
      },
      onConnected() {
        closeToast()
        const session = useSessionStore()
        session.updateActionState(FAction.AGENT)
        // 链接成功后关闭机器人定时器worker
        closeRobotWorker()
        if (connectType === 'init') {
          const msgId = uuidv7()
          send(JSON.stringify({
              type: '@imCloud_subject_message_reqagent@',
              mid: 'm_' + uuidv7(),
              sessionId: session.sessionId,
              meetingId: session.meetingId,
              configId: session.configId,
              msg: {
                brand: session.brand,
                loginName: session.visitorInformation.name,
                skillId: transferMenu.masterSkillId,
                menu: transferMenu.menuName,
                menuId: transferMenu.id,
                visitorId: session.visitorInformation.visitorId,
                dicOrder: 1,
              },
            }))
          // 链接上后如果有未读消息的话先更新未读消息状态
          if (session.unReadMessageState) {
            send(JSON.stringify({
                    msg: {
                        visitorId: session.visitorInformation.visitorId,
                    },
                    type: '@type_message_read@',
                    mid: msgId,
                    messageUUID: msgId,
                    configId: session.configId,
                    meetingId: session.meetingId,
                    sessionId: session.sessionId,
                }))
            session.updateUnReadMessageState(false)
          }
        }
      },
      onMessage(...args) {
        const event = args[1]
        const message = JSON.parse(event.data)
        if (
          message.type !== 'server_reply' &&
          message.currentType !== 'page_ht'
        ) {
          send(
            JSON.stringify({
              type: 'page_reply',
              mid: message.mid,
              configId: session.configId,
              meetingId: session.meetingId,
              sessionId: session.sessionId,
            }),
          )
        }
        switch (message.type) {
          case '@imCloud_subject_message_reqcallback@':
            // 系统主动推送到客户端数据
            handleSocketMessage(message)
            break
          case '@imCloud_subject_message_system@':
            handleSocketMessage(message)
            break
          case '@imCloud_subject_meeting_destroy@':
            // 会议室销毁
            handleSocketMessage(message)
            break
          case '@imCloud_subject_message_user@':
            // 用户消息
            handleUserMessage(message)
            break
          case '@imCloud_subject_user_survey@':
            // 坐席邀请评价
            handleSocketMessage(message)
            break
          case '@type_cancel_queue@':
              handleSocketMessage(message)
            break
          default:
            break
        }
      },
      onError(error) {
        console.log('websocket连接错误', error)
      },
      async onDisconnected() {
        console.log('websocket连接关闭')
      },
    })
    this.status = status
    this.data = data
    this.send = send
    this.close = close
  }
  sendMessage(
    value: any,
    type: string = '@imCloud_subject_message_user@',
    callback: () => void,
  ) {
    const session = useSessionStore()
    const msgId = uuidv7()
    if (type === '@imCloud_subject_message_user@' || type === 'queue_msg') {
      this.send(
        JSON.stringify({
          msg: {
            contentType: 1,
            contentMsgType: 1,
            htmlContent: value,
            content: value,
            voice: false,
            visitorId: session.visitorInformation.visitorId,
            kmId: '',
          },
          type: type,
          configId: session.configId,
          meetingId: session.meetingId,
          sessionId: session.sessionId,
          mid: msgId,
          messageUUID: msgId,
          errorMsg: value || '发送失败',
        }),
      )
    } else if (type === '@type_cancel_queue@') {
        this.send(
            JSON.stringify({
                msg: {
                    contentType: 'VisitorClose'
                },
                type: type,
                mid: msgId,
                messageUUID: msgId,
                configId: session.configId,
                meetingId: session.meetingId,
                sessionId: session.sessionId,
            }),
        )
    } else if (type === '@imCloud_subject_meeting_destroy@') {
        // 访客主动结束
        this.send(JSON.stringify({
            mid: msgId,
            messageUUID: msgId,
            configId: session.configId,
            meetingId: session.meetingId,
            sessionId: session.sessionId,
            ...value
        }))
    } else {
      // 消息已读type=@type_message_read@
      this.send(
        JSON.stringify({
          msg: {
            visitorId: session.visitorInformation.visitorId,
          },
          type: type,
          mid: msgId,
          messageUUID: msgId,
          configId: session.configId,
          meetingId: session.meetingId,
          sessionId: session.sessionId,
        }),
      )
    }
    callback()
  }
  closeSocket() {
    this.close()
  }
}

export default new SocketServer()
